package com.shouhuyun.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.shouhuyun.constant.MessageConstant;
import com.shouhuyun.constant.RedisConstant;
import com.shouhuyun.entity.PageResult;
import com.shouhuyun.entity.QueryPageBean;
import com.shouhuyun.entity.Result;
import com.shouhuyun.pojo.Role;
import com.shouhuyun.pojo.User;
import com.shouhuyun.pojo.CheckItem;
import com.shouhuyun.pojo.User;
import com.shouhuyun.service.UserService;
import com.shouhuyun.utils.QiniuUtils;
import com.shouhuyun.pojo.EditPassword;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.List;
import java.util.UUID;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.xml.ws.Service;

/**
 * 用户相关操作
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Reference
    private UserService userService;
    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        try {
            return userService.Pagequery(queryPageBean);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // 获取当前登录的用户的用户名
    @RequestMapping("/getUsername")
    public Result getUsername(){

        //springSecurity 完成认证后  会把用户信息保存到框架提供的上下文对象  底层基于session
        /**
         *    SecurityContextHolder类似于工具类
         *    SecurityContextHolder.getContext()  上下文对象
         *    SecurityContextHolder.getContext().getAuthentication()  认证信息对象
         *    getPrincipal  拿到的 框架提供的 User对象
         */

        try{
            org.springframework.security.core.userdetails.User user =
                    (org.springframework.security.core.userdetails.User)
                            SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (user != null){
                String username = user.getUsername();

                User byUsername = userService.findByUsername(username);
//                String img = byUsername.getImg();
                return new Result(true, MessageConstant.GET_USERNAME_SUCCESS, byUsername);
            }
            return new Result(false,MessageConstant.GET_USERNAME_FAIL+"用户名为空");
        }catch (Exception e){
            return new Result(false, MessageConstant.GET_USERNAME_FAIL);
        }

    }

    @RequestMapping("/add")
    public Result add(@RequestBody User user, Integer[] roleIds) {
        try {
            userService.add(user, roleIds);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_USER_FAIL);
        }
    }

    //文件上传
    //注意spring-mvc里要配置文件上传组件
    @RequestMapping("/upload")
    public Result upload(@RequestParam("imgFile") MultipartFile imgFile) {
        //        测试 文件是否能 传到后台
//        System.out.println(imgFile);
//          获取原始文件后缀
        String originalFilename = imgFile.getOriginalFilename();  //原始文件名
        int index = originalFilename.lastIndexOf(".");
        String extention = originalFilename.substring(index); //  .jpg
//        通过UUID  获取一个36位的随机名
        String fileName = UUID.randomUUID().toString() + extention;

        try {
//          通过七牛云传到七牛云服务器
            QiniuUtils.upload2Qiniu(imgFile.getBytes(),fileName);
//          将上传图片名称存入Redis，基于Redis的Set集合存储
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES, fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
        }
        return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS, fileName);
    }

    @RequestMapping("/edit")
    public Result edit(Integer[] userIds, Integer[] roleIds) {
        Integer userId = userIds[0];
        try {
            userService.edit(userId, roleIds);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_ROLE_FAIL);
        }
        return new Result(true, MessageConstant.ADD_ROLE_SUCCESS);
    }

    @RequestMapping("/findById")
    public Result findById(Integer id) {
        System.out.println("sdf");
        try {
            List<Integer> roleList = userService.findById(id);
            return new Result(true, MessageConstant.QUERY_Role_SUCCESS, roleList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_Role_FAIL);
        }
    }

    //    删除用户
    @RequestMapping("/delete")
    public Result delete(Integer id) {
        try {
            userService.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
            //服务调用失败
            return new Result(false, MessageConstant.DELETE_USER_FAIL);
        }
        return new Result(true, MessageConstant.DELETE_USER_SUCCESS);
    }
}
